package com.ninthgroup.aop;

import com.alibaba.excel.util.StringUtils;
import com.ninthgroup.controller.DoctorController;
import com.ninthgroup.entity.Admin;
import com.ninthgroup.entity.Doctor;
import com.ninthgroup.entity.Log;
import com.ninthgroup.entity.User;
import com.ninthgroup.service.LogService;
import com.ninthgroup.util.WebUtil;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Date;

/**
 * @author ：1452863884@qq.com rcg
 * @date ：Created in 2022/11/3 19:18
 * @description：登录的日志aop
 * 这个是排除单方法的切入点
 * && !execution(* com.ninthgroup.controller.LoginController.getusername(..))
 * @modified By：
 * @version:1.0
 */
@Component
@Aspect
public class LogAop {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogAop.class);
    //开始时间
    private Date visitTime;
    //访问的方法全路径
    private String method;
    //获取方法参数类型
    private String methodParType;
    //获取方法参数名
    private String methodParName;
    //获取方法参数值
    private String methodParvalue;
    //获取方法返回值
    private String methodReturn;

    //定义一个共有的名字
   private static String presentName = "";

    private static Class<?> clazz = null;

    private static final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();


    @Autowired
    private LogService logService;

    //前置通知,主要是获取开始时间，执行的类是哪一个，执行的是哪一个方法
    @Before("execution(* com.ninthgroup.controller.LoginController.*(..)) && !execution(* com.ninthgroup.controller.LoginController.getusername(..)) && !execution(* com.ninthgroup.controller.LoginController.layout(..))") //需要拦截的路径
    public void doBefore(JoinPoint jp) throws ClassNotFoundException, NoSuchMethodException {

        //当前时间就是开始访问的时间
        visitTime = new Date();
        //具体要访问的类
        clazz = jp.getTarget().getClass();
        //获取访问的方法的名称
        String methodName = jp.getSignature().getName();
        //方法全路径
        method = jp.getTarget().getClass().getName() + "." + methodName;

        Object[] args = jp.getArgs();//获取访问的方法的参数 值
        LOGGER.info("参数值:" + Arrays.toString(args));
        methodParvalue = Arrays.toString(args);

        Class[] paramTypes = null;  //获取参数类型
        Method[] methods = clazz.getMethods();

        for (int i = 0; i < methods.length; i++) {
            if (methodName.equals(methods[i].getName())) {//和传入方法名匹配
                Class[] params = methods[i].getParameterTypes();
                paramTypes = new Class[params.length];
                for (int j = 0; j < params.length; j++) {
                    paramTypes[j] = Class.forName(params[j].getName());
                }
                break;
            }
        }
        LOGGER.info("参数的类型:" + Arrays.toString(paramTypes));
        methodParType = Arrays.toString(paramTypes);


        //spring中的 类  用于获取方法的参数名称
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        //获取方法的 全部的参数名称
        String[] params = u.getParameterNames(clazz.getMethod(methodName, paramTypes));
        LOGGER.info("参数名称:" + Arrays.toString(params));
        methodParName = Arrays.toString(params);

        //获方法的返回值类型
        Type t = clazz.getMethod(methodName, paramTypes).getAnnotatedReturnType().getType();
        LOGGER.info("方法的返回值类型:" + t);
        methodReturn = t.toString();

        LOGGER.info("执行前置通知了");

        //获取请求方法全限定名  包括参数 参数名称

    }

    //后置通知  如果出现异常就不执行
    @After("execution(* com.ninthgroup.controller.LoginController.*(..)) && !execution(* com.ninthgroup.controller.LoginController.getusername(..)) && !execution(* com.ninthgroup.controller.LoginController.layout(..))")
    public void doAfter(JoinPoint jp) throws Exception {
        String url = "";

        //得到UserAgent对象
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        //获得浏览器信息

        Browser browser = userAgent.getBrowser();
        String browsers = browser + "";
        System.out.println("浏览器    " + browsers);
        //获得操作系统信息
        OperatingSystem os = userAgent.getOperatingSystem();
        String oss = os + "";
        System.out.println("os  " + oss);
        //获得ip信息
        String ip = "";
        try {
            //ip 地址
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        System.out.println("ip   " + ip);

        //获取用户ip地址

        //获取当前操作的用户

        HttpSession session = WebUtil.getSession();
        User user = (User) session.getAttribute("user");
        Admin admin = (Admin) session.getAttribute("admin");
        Doctor doctor = (Doctor) session.getAttribute("doctor");

        if (user != null) {
            presentName = user.getRealname();
            session.removeAttribute("user");
        }

        if (admin != null) {
            presentName = admin.getaName();
            session.removeAttribute("admin");
        }

        if (doctor != null) {
            presentName = doctor.getdName();
            session.removeAttribute("doctor");
        }
        //调用Service完成插入操作
        // 使用StringUtils工具类，判断不为null也不是空，
        if(StringUtils.isNotBlank(ip) && StringUtils.isNotBlank(browsers) && StringUtils.isNotBlank(oss)){
            String tool="浏览器:"+browsers+"操作系统:"+oss;
            Log log = new Log(presentName,new Date(),ip,tool);
            logService.save(log);
        }

        LOGGER.info("执行最终通知");
    }


}